import { pick, cloneDeep } from 'lodash-es'

let KEY_MAPPING = 'KEY_MAPPING'
let VALUE_MAPPING = 'VALUE_MAPPING'
let ARRAY_VALUE_MAPPING = 'ARRAY_VALUE_MAPPING'
let ARRAY_PLACEHOLDER = 'ARRAY_PLACEHOLDER'
let PLACEHOLDER = 'PLACEHOLDER'
let PLACEHOLDER_MAPPING = 'PLACEHOLDER_MAPPING'

let FULL_SIGN = '。'
let COMMA_SIGN = '，'

// 病历名词
const EMR_NAME = {
  // chilefComplaint
  cough: '咳嗽',
  wheezing: '喘息',
  year: '年',
  month: '个月',
  week: '周',
  day: '天',

  // repeatReason
  reCough: '咳嗽',
  reWheezing: '喘息',
  reChestTightness: '胸闷',
  reShortnessBreath: '气促',
  reExpectoration: '咳痰',
  reExpectorationColor: '痰色',
  yellow: '黄痰',
  white: '白痰',
  rePhlegm: '痰鸣',
  repeatOthers: '',

  // multiReason
  cold: '感冒',
  movement: '剧烈运动',
  yell: '大叫、大笑',
  scream: '哭闹',
  takeFood: '进食甜食或冷冻食品饮料',
  climateChange: '气候变化',
  causeOthers: '',

  // fluquency
  morning: '晨起',
  evening: '晚上尤其是入睡后',

  // season
  seasonCorrelation: '在某些季节容易发病',
  spring: '春季',
  summer: '夏季',
  fall: '秋季',
  winter: '冬季',

  ususal: '如常',
  less: '减少',
  none: '拒食',
  normal: '正常',
  abnormal: '异常',
  // 可用
  valid: { 0: '无效', 1: '有效' },
  had: { 0: '无', 1: '有' },

  father: '父',
  mother: '母',
  siblings: '同胞',
  elderBrother: '哥哥',
  elderSister: '姐姐',
  youngerBrother: '弟弟',
  youngerSister: '妹妹',

  positive: '阳性',
  negative: '阴性',

  // 学龄前喘息
  indicateAsthm: '症状特征提示哮喘',
  asthmaPositive: '哮喘预测指数（mAPI）阳性',
  frequentSeizures: '频繁发作',
  causeStrongly: '严重发作',
  frequentDelays: '症状频繁迁延',
}

let serializeUtils = {
  parse: function (
    keys,
    data,
    { main = null, connector = '', prefix = '', suffix = '' }
  ) {
    // 控制着模块中的sub sentences
    if (main && !main()) return ''

    let _parse = function (item, data) {
      let {
        type,
        key,
        alias = '',
        prefix = '',
        suffix = '',
        connector = '',
        children = {},
      } = item
      let value = data[key]
      let ret = []
      // KEY_MAPPING: key隐射到Config.js 定义中的遍历
      if (type == KEY_MAPPING) {
        ret = [
          { key, value: key, mapping: EMR_NAME[alias || key], prefix, suffix },
        ]
      }
      // VALUE_MAPPING: value隐射到Config.js 定义中的遍历
      if (type == VALUE_MAPPING) {
        ret = [{ key, value: key, mapping: EMR_NAME[value], prefix, suffix }]
      }
      // 数组的隐射值
      if (type == ARRAY_VALUE_MAPPING) {
        // value 是个数组
        ret = value.map((item) => {
          return {
            key: key,
            value: item,
            mapping: EMR_NAME[alias || item],
            prefix,
            suffix,
          }
        })
      }
      // 数组的占位符
      if (type == ARRAY_PLACEHOLDER) {
        // value 是个数组
        ret = value.map((item) => {
          return { key: key, value: item, mapping: item, prefix, suffix }
        })
      }
      // PLACEHOLDER: 固有的值
      if (type == PLACEHOLDER) {
        ret = [{ key, value, mapping: value, prefix, suffix }]
      }
      // PLACEHOLDER_MAPPING: 固有的值 + 隐射到config.js 定义的变量
      if (type == PLACEHOLDER_MAPPING) {
        ret = [
          {
            key,
            value,
            mapping: value + EMR_NAME[alias || key],
            prefix,
            suffix,
          },
        ]
      }

      // 如果有render 方法,则覆盖上面所有的返回
      if (item.render) {
        ret = [
          { key, value, mapping: item.render(value, data), prefix, suffix },
        ]
      }

      // if has children
      if (children && children.isRelated) {
        ret = ret.map((r) => {
          if (children.isRelated(r.value)) {
            r.mapping += serializeUtils.parse(
              children.keys,
              data,
              pick(children, ['prefix', 'connector', 'suffix'])
            )
          }
          return r
        })
      }

      let retStr = ret
        .map((r) => {
          return r.prefix + r.mapping + r.suffix
        })
        .join(connector)

      return retStr
    }

    let content = keys
      .filter((item) => {
        let val = data[item.key]
        if (Object.prototype.toString.call(val) === '[object Array]')
          return val.filter((item) => item).length

        // q1: false 值的显示不出来
        // q2: 主诊为false 需要过滤
        return val !== '' && val != undefined
      }) // 过滤转化前, 为空的数据
      .map((item) => {
        let ret = _parse(item, data)
        return ret
      })
      .filter((item) => item) // 过滤转化后, 为空的数据
      .join(connector)

    return content ? prefix + content + suffix : ''
  },
  isPass(prediction) {
    return !!prediction
  },
  commas(content) {
    let lastChar =
      (typeof content == 'string' && content && content.slice(-1)) || ''
    if (content && ![COMMA_SIGN, FULL_SIGN].includes(lastChar))
      return COMMA_SIGN
    return ''
  },
  isNotNull(data) {
    return data !== undefined && data !== null
  },
  isValid(value) {
    if (typeof value == 'boolean') return true
    if (typeof value == 'string') return value
    if (typeof value == 'number') return isNaN(value)
    if (value === null || value === undefined) return false
    return false
  },
  autoJoin(sentences, data, opts = {}, childOpts = {}) {
    let ret = sentences
      .map((item) => {
        let args = [
          data,
          childOpts.prefix,
          childOpts.suffix,
          childOpts.connector,
        ]
        return item.apply(null, args)
      })
      .filter((item) => item)
      .join(opts.connector ? opts.connector : COMMA_SIGN)
      .trim()

    // let fullSignIdx = ['.', '。', ',', ';'].indexOf(ret.slice(-1));
    // if (fullSignIdx == -1 && ret) {
    //   ret += '。';
    // }

    ret = serializeUtils.autoFullSign(ret)
    return ret
  },
  autoFullSign(content) {
    content = content.trim()
    if (!content) return ''

    if ([',', ';', '。', '.', '．'].indexOf(content.slice(-1)) == -1) {
      content += FULL_SIGN
    }
    return content
  },
  randomCombination(data, keys) {
    return keys
      .filter((item) => data[item.key])
      .map((item) => {
        return data[item.key] + EMR_NAME[item.alias]
      })
      .join('')
  },
}
/* eslint-disable */
/**
 * subSentences:[@fn] 函数定义的规则
 * function @fn(){```
 *   prefix:"这是一个分句的开始部分",
 *   suffix:"这是一个分局的结束部分",
 *   connector:"一个分局中多个变量之间的连接符号"
 *   keys:[{key:'属性名', type: KEY_MAPPING, alias:'属性名称的别名'}],
 *      @type类型 在serializeUtils.parse function 有介绍
 *      @key类型 对应变量的名称
 *      @alias  对应变量的别名, 多个key类型可能对应一个alias, 比如key是`reYears, years`, 别名都是year, 返回`年`
 *   children: @children的命名为具体的关联的属性 如果某一个key有关联的子项目, 比如勾选框`其他`, 后面需要填写备注, 则返回`其他(备注的具体内容)`. @isRelated 返回为true的时候, 才显示当前的children对应的内容
 * }
 */
/* eslint-enable */
export const serialize = {
  chiefComplaint: function (vm) {
    let chiefComplaint = vm.chiefComplaint
    if (!chiefComplaint) return ''

    // main 控制整句是否有效
    if (
      serializeUtils.isPass(
        !chiefComplaint.cough &&
          !chiefComplaint.wheezing &&
          !chiefComplaint.remark
      )
    )
      return ''

    let isNotValid = serializeUtils.isPass(
      !chiefComplaint.cough && !chiefComplaint.wheezing
    )

    // sub sentences
    let subSentences = [
      function (data) {
        let prefixOne = '反复',
          content = ''

        if (data.cough && data.wheezing) {
          content += prefixOne + EMR_NAME.cough + '伴' + EMR_NAME.wheezing
        } else if (data.cough) {
          content += prefixOne + EMR_NAME.cough
        } else if (data.wheezing) {
          content += prefixOne + EMR_NAME.wheezing
        }

        let prefixTwo = '发作'
        let keys = [
          { key: 'years', alias: 'year' },
          { key: 'months', alias: 'month' },
          { key: 'days', alias: 'day' },
        ]

        // keys 随意组合
        let recent = serializeUtils.randomCombination(data, keys)
        recent = recent ? prefixTwo + recent : ''

        return isNotValid ? '' : content + recent
      },
      function (data) {
        let prefix = '再发'
        let keys = [
          { key: 'reYears', alias: 'month' },
          { key: 'reMonths', alias: 'day' },
        ]

        // keys 随意组合
        let content = serializeUtils.randomCombination(data, keys)
        return isNotValid ? '' : content ? prefix + content : ''
      },
      function (data) {
        let keys = [{ key: 'remark', type: PLACEHOLDER }]
        let content = serializeUtils.parse(keys, data, {})
        return content
      },
    ]

    let ret = serializeUtils.autoJoin(subSentences, chiefComplaint)
    return ret
  },
  repeatReason: function (vm) {
    let presentIllnessHistory = cloneDeep(vm.presentIllnessHistory)
    if (!presentIllnessHistory) return ''

    // main
    if (
      serializeUtils.isPass(
        !presentIllnessHistory.cough &&
          !presentIllnessHistory.wheezing &&
          !presentIllnessHistory.repeatRemark
      )
    )
      return ''

    // let timeUnit = ['小时', '天', '日', '星期', '周', '月', '季', '年'];

    let subSentences = [
      function (data) {
        // `患儿自${gen('startYear')}年${gen('startMonth')}月开始出现
        let content = ''
        if (data.startYear || data.startMonth) {
          let dateStr = data.startYear ? data.startYear + '年' : ''
          dateStr += data.startMonth ? data.startMonth + '月' : ''
          if (!dateStr) return ''
          content += `患儿自${dateStr}开始出现`
        }

        //  ${gen('cough')}反复咳嗽,${gen('wheezing')}伴喘息发作,
        if (data.cough && data.wheezing) {
          content += '反复咳嗽, 伴喘息发作'
        } else if (data.cough) {
          content += '反复咳嗽'
        } else if (data.wheezing) {
          content += '反复喘息发作'
        }

        return content
      },
      function (data) {
        // 至今共发作1次, 过去1年共发作1次
        let content = ''
        if (data.timesInTotal) {
          content += `至今共发作${data.timesInTotal}次`
        }
        if (data.timesInPastYears) {
          content +=
            serializeUtils.commas(content) +
            `过去1年共发作${data.timesInPastYears}次`
        }
        return content
      },
      function (data) {
        //近3个月共发作1次
        let content = ''
        if (data.timesInRecentMonths) {
          content += `近3个月共发作${data.timesInRecentMonths}次`
        }
        return content
      },
      function (data) {
        // 每次发作症状迁延时间1天
        let content = ''
        if (data.rePhlegmTime) {
          content += `每次发作症状迁延时间${data.rePhlegmTime}天`
        }
        return content
      },
      function (data) {
        // 是否有需要使用全身糖皮质激素、急诊、住院的急性发作: 这种严重发作曾在6个月内发作1次
        let content = ''
        if (data.breakOutAcute !== null && data.breakOutAcute != undefined) {
          content += `${
            data.breakOutAcute ? '' : '不'
          }需要使用全身糖皮质激素、急诊、住院的急性发作`
        }

        if (content && data.breakOutInSixMonth) {
          content += `${COMMA_SIGN}这种严重发作曾在6个月内发作${data.breakOutInSixMonth}次`
        }

        return content
      },
      function (data) {
        // 在过去4周或更长时间，是否每周有症状并需要治疗,治疗1天
        let content = ''
        if (data.treatEachWeek !== null && data.treatEachWeek != undefined) {
          content += `在过去4周或更长时间，${
            data.treatEachWeek ? '' : '不是'
          }每周有症状并需要治疗`
        }

        // if (data.treatEachWeek && data.treatDaysEachWeek) {
        //   content += `${COMMA_SIGN}治疗${data.treatDaysEachWeek}天`;
        // }
        return content
      },
      function (data) {
        //过去4周共有 咳嗽1天/喘息发作 1次
        let content = ''
        if (!data.coughInPastFourWeek && !data.wheezInPastFourWeek)
          return content

        if (data.coughInPastFourWeek) {
          content += `咳嗽${data.coughInPastFourWeek}天`
        }
        if (data.wheezInPastFourWeek) {
          content +=
            (data.coughInPastFourWeek ? '/' : '') +
            `喘息发作${data.wheezInPastFourWeek}次`
        }

        return `过去4周共有${content}`
      },
      function (data) {
        // 过去4周需要使用药物缓解咳嗽/咳喘症状总有1次。
        let content = ''
        if (data.laxationInPastFourWeek) {
          content += `过去4周需要使用药物缓解咳嗽/咳喘症状总有${data.laxationInPastFourWeek}次`
        }
        return content
      },
      function (data) {
        //  近${gen('daysRecent')}天再次出现,
        let content = ''
        if (data.daysRecent) {
          content += `近${data.daysRecent}天再次出现`
        }
        return content
      },
      function (data) {
        // 咳嗽、喘息、胸闷、 气促、咳痰, 黄/白
        let keys = [
          'reCough',
          'reWheezing',
          'reChestTightness',
          'reShortnessBreath',
          'reExpectoration',
        ]
        let content = ''
        let color = ''

        let filterKeys = keys.filter((item) => data[item])
        content = filterKeys.map((item) => EMR_NAME[item]).join(COMMA_SIGN)

        if (data.reExpectoration && data.reExpectorationColor) {
          color = `(${EMR_NAME[data.reExpectorationColor]})`
        }

        content += color

        if (data.rePhlegm) {
          content += COMMA_SIGN + `${EMR_NAME['rePhlegm']}`
        }

        return content
      },
      function (data) {
        // 是否有发热
        let content = ''
        if (serializeUtils.isNotNull(data.hasFever)) {
          content += `${data.hasFever ? '有' : '无'}发热`
        }
        if (content && data.temperature) {
          content += `体温${data.temperature}°C`
        }
        return content
      },
      function (data) {
        // 是否有流鼻涕
        let content = ''
        if (serializeUtils.isNotNull(data.hasMucus)) {
          content += `${data.hasMucus ? '有' : '无'}流鼻涕`
        }
        return content
      },
      function (data) {
        // 喘息之前是否有吃东西呛过
        let content = ''
        if (serializeUtils.isNotNull(data.hasChokeBefore)) {
          content += `喘息之前${data.hasChokeBefore ? '有' : '无'}吃${
            (data.hasChokeBefore && data.chokeRemark) || '东西'
          }呛过`
        }

        return content
      },
      function (data) {
        // 有使用抗生素治疗，使用了52天
        let content = ''
        if (serializeUtils.isNotNull(data.hasUseAntibiotic)) {
          content += `${data.hasUseAntibiotic ? '曾' : '沒有'}使用抗生素治疗`
        }
        if (content && data.usingAntibioticDays) {
          content += `${data.usingAntibioticDays}天`
        }

        if (content && serializeUtils.isNotNull(data.isAntibioticWork)) {
          content += `，症状${data.isAntibioticWork ? '有所' : '没有'}缓解`
        }
        return content
      },
      function (data) {
        // 其它
        return data.repeatRemark || ''
      },
    ]
    return (
      serializeUtils.autoJoin(subSentences, presentIllnessHistory) + '\r\n\r\n'
    )
  },
  multiReason: function (vm) {
    // 每次发作的诱发因素:感冒,接触动物浓烈的气味,孩子有否在跑动或玩耍过程中因为咳嗽、气喘或气促被迫停下来：是/否   ，
    // 近4周是否有出现:是/否  。 有否正常上体育课：是/否 ，跑步是否比大多数同学慢：是/否 ，跑步测验是否达标：是/否。

    let presentIllnessHistory = cloneDeep(vm.presentIllnessHistory)
    let causeChecks = presentIllnessHistory.causeChecks
    let content = ''

    if (causeChecks.length) {
      content += ''
      let touchAnimalsIdx = causeChecks.indexOf('touchAnimals')
      if (touchAnimalsIdx != -1) causeChecks.splice(touchAnimalsIdx, 1)
      let strongSmellIdx = causeChecks.indexOf('strongSmell')
      if (strongSmellIdx != -1) causeChecks.splice(strongSmellIdx, 1)

      let causeCheckStrs = causeChecks.map((item) => {
        return EMR_NAME[item]
      })

      // 接触动物
      if (touchAnimalsIdx != -1) {
        let aniamal = presentIllnessHistory.touchAnimalsContent
        if (aniamal) causeCheckStrs.push(`接触动物(${aniamal})`)
        else {
          causeCheckStrs.push('接触动物')
        }
      }

      // 浓烈的气味
      if (strongSmellIdx != -1) {
        let smell = presentIllnessHistory.stongSmellContent
        if (smell) causeCheckStrs.push(`闻到浓烈的气味(${smell})`)
        else {
          causeCheckStrs.push('闻到浓烈的气味')
        }
      }

      content += causeCheckStrs.join(COMMA_SIGN) + '可诱发咳嗽或喘息发作。'
    } else {
      content += '无诱发咳嗽或喘息发作。'
    }

    let schoolSituation = []
    if (serializeUtils.isNotNull(presentIllnessHistory.forcedStopByCough)) {
      schoolSituation.push(
        `孩子${
          presentIllnessHistory.forcedStopByCough ? '有' : '没有'
        }在跑动或玩耍过程中因为咳嗽、气喘或气促被迫停下来`
      )
    }
    if (
      presentIllnessHistory.forcedStopByCough &&
      serializeUtils.isNotNull(presentIllnessHistory.appearInPastFourWeek)
    ) {
      schoolSituation.push(
        `近4周${presentIllnessHistory.appearInPastFourWeek ? '有' : '没有'}出现`
      )
    }
    if (serializeUtils.isNotNull(presentIllnessHistory.normalInPE)) {
      schoolSituation.push(
        `${presentIllnessHistory.normalInPE ? '有' : '没有'}正常上体育课`
      )
    }
    if (serializeUtils.isNotNull(presentIllnessHistory.isRunSlower)) {
      schoolSituation.push(
        `跑步${presentIllnessHistory.isRunSlower ? '有' : '没有'}比大多数同学慢`
      )
    }
    if (serializeUtils.isNotNull(presentIllnessHistory.passRunningTest)) {
      schoolSituation.push(
        `跑步测验${presentIllnessHistory.passRunningTest ? '有' : '没有'}达标`
      )
    }

    if (schoolSituation.length) {
      content +=
        serializeUtils.commas(content) + schoolSituation.join(COMMA_SIGN)
    }

    if (presentIllnessHistory.causeRemark) {
      content +=
        serializeUtils.commas(content) + presentIllnessHistory.causeRemark
    }

    content = serializeUtils.autoFullSign(content)
      ? serializeUtils.autoFullSign(content) + '\r\n\r\n'
      : ''

    return content
  },
  fluquency: function (vm) {
    // '晨起晚上尤其是入睡后症状好发或加重。';
    let moData = vm.presentIllnessHistory
    let content = ''
    if (!moData) return content

    if (moData.morning && moData.evening) {
      content += '晨起、晚上尤其是入睡后症状好发或加重'
    } else if (moData.morning || moData.evening) {
      content += `${moData.morning ? '晨起' : ''}${
        moData.evening ? '晚上尤其是入睡后' : ''
      }症状好发或加重`
    }

    if (serializeUtils.isNotNull(moData.wakeUpByAsthma)) {
      content +=
        serializeUtils.commas(content) +
        `过去4周睡眠过程中${
          moData.wakeUpByAsthma ? '有过' : '没有'
        }因咳嗽、气喘醒来`
    }

    if (moData.timeRhythmRemark) {
      content += serializeUtils.commas(content) + moData.timeRhythmRemark
    }

    content = serializeUtils.autoFullSign(content)
      ? serializeUtils.autoFullSign(content) + '\r\n\r\n'
      : ''
    return content
  },
  season: function (vm) {
    // '是否在某些季节容易发病,好发季节春季夏季秋季冬季';
    let moData = vm.presentIllnessHistory
    let content = ''
    if (!moData) return content

    if (serializeUtils.isPass(moData.seasonCorrelation === '0'))
      return '症状与季节无明显相关。' + '\r\n\r\n'

    if (
      serializeUtils.isPass(
        moData.seasonChecks.length === 0 && !moData.seasonRemark
      )
    )
      return '症状与季节无明显相关。' + '\r\n\r\n'

    if (moData.seasonChecks.length) {
      let seasonNames = moData.seasonChecks.map((item) => EMR_NAME[item])
      content += `在${seasonNames.join('、')}好发`
    }
    if (moData.seasonRemark) {
      content += ((content && ',') || '') + moData.seasonRemark
    }

    content += ((content && '。') || '') + '\r\n\r\n'

    return content
  },
  reveribility: function (vm) {
    // '既往哮喘药物治疗情况 既往哮喘药物治疗情况缓解药物有效无效。控制药物A.B使用月周日有效无效。两次发作之间是否有完全缓解期有无';
    let presentIllnessHistory = vm.presentIllnessHistory
    if (!presentIllnessHistory) return ''
    if (serializeUtils.isPass(!presentIllnessHistory.relieverMedicants == '1'))
      return ''
    let subSentences = [
      (data) => {
        let main = () => !!data.isAsthmaCured.length
        let keys = [
          {
            key: 'isAsthmaCured',
            type: PLACEHOLDER,
            render(value) {
              return value ? '曾使用过药物' : ''
            },
          },
        ]
        return serializeUtils.parse(keys, data, { main, prefix: '' })
      },
      (data) => {
        let main = () => !!data.relieverMedicants.length
        let keys = [
          {
            key: 'relieverMedicants',
            type: PLACEHOLDER,
            render(value) {
              let ret = value.join('、') || ''
              if (ret) {
                ret += '等缓解治疗药物'
              }

              if (
                ret &&
                data.relieverWork != '' &&
                data.relieverWork != null &&
                data.relieverWork != undefined
              ) {
                ret += '治疗' + EMR_NAME.valid[data.relieverWork]
              }
              return ret
            },
          },
        ]
        return serializeUtils.parse(keys, data, {
          main,
          prefix: '既往使用过：',
        })
      },
      (data) => {
        let main = () => !!data.relieverMedicants.length
        let keys = [
          {
            key: 'relieverUseYears',
            alias: 'year',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'relieverUseMonths',
            alias: 'month',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'relieverUseWeeks',
            alias: 'week',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'relieverUseDays',
            alias: 'day',
            type: PLACEHOLDER_MAPPING,
          },
        ]
        return serializeUtils.parse(keys, data, { main, prefix: '使用' })
      },
      (data) => {
        let main = () => !!data.controllerMedicantUse.length
        let keys = [
          {
            key: 'controllerMedicantUse',
            type: PLACEHOLDER,
            render: (value) => {
              let ret = value.join('、') || ''
              if (ret) {
                ret += '控制药物'
              }
              if (
                ret &&
                data.controllerMedicantWork != '' &&
                data.controllerMedicantWork != null &&
                data.controllerMedicantWork != undefined
              ) {
                ret += '治疗' + EMR_NAME.valid[data.controllerMedicantWork]
              }
              return ret
            },
          },
        ]
        return serializeUtils.parse(keys, data, {
          main,
          prefix: '使用过：',
          suffix: '',
        })
      },
      (data) => {
        let main = () => !!data.controllerMedicantUse.length
        let keys = [
          {
            key: 'useYears',
            alias: 'year',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'useMonths',
            alias: 'month',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'useWeeks',
            alias: 'week',
            type: PLACEHOLDER_MAPPING,
          },
          {
            key: 'useDays',
            alias: 'day',
            type: PLACEHOLDER_MAPPING,
          },
        ]
        return serializeUtils.parse(keys, data, { main, prefix: '使用' })
      },
      (data) => {
        let main = () => {
          return !!data.pauseBetweenCause
        }
        let keys = [
          {
            key: 'pauseBetweenCause',
            render: (value) => {
              return EMR_NAME.had[value] || ''
            },
            prefix: '',
            suffix: '',
          },
        ]
        return serializeUtils.parse(keys, data, {
          main,
          prefix: '两次发作之间',
          suffix: '完全缓解期',
        })
      },
      (data) => {
        if (!data.reversibilityRemark) return
        let main = () => !!data.reversibilityRemark.length
        let keys = [
          {
            key: 'reversibilityRemark',
            type: PLACEHOLDER,
            render(value) {
              return value ? value : ''
            },
          },
        ]
        return serializeUtils.parse(keys, data, { main, prefix: '其他备注：' })
      },
    ]
    return serializeUtils.autoJoin(subSentences, presentIllnessHistory)
  },
  otherPersonality: function (vm) {
    let presentIllnessHistory = cloneDeep(vm.presentIllnessHistory)
    let content = ''
    if (EMR_NAME[presentIllnessHistory.appetite]) {
      content += '胃纳' + EMR_NAME[presentIllnessHistory.appetite]
    }
    if (
      serializeUtils.isNotNull(presentIllnessHistory.vomit) &&
      presentIllnessHistory.vomit !== ''
    ) {
      content +=
        serializeUtils.commas(content) +
        `${presentIllnessHistory.vomit ? '有' : '无'}呕吐`
      if (presentIllnessHistory.vomitRemark) {
        content += `${presentIllnessHistory.vomitRemark})`
      }
    }
    if (
      serializeUtils.isNotNull(presentIllnessHistory.feces) &&
      EMR_NAME[presentIllnessHistory.feces]
    ) {
      content +=
        serializeUtils.commas(content) +
        `大便${EMR_NAME[presentIllnessHistory.feces]}`
      if (presentIllnessHistory.fecesRemark) {
        content += `(${presentIllnessHistory.fecesRemark})`
      }
    }
    if (
      serializeUtils.isNotNull(presentIllnessHistory.urine) &&
      EMR_NAME[presentIllnessHistory.urine]
    ) {
      content +=
        serializeUtils.commas(content) +
        `小便${EMR_NAME[presentIllnessHistory.urine]}`
      if (presentIllnessHistory.urineRemark) {
        content += `(${presentIllnessHistory.urineRemark})`
      }
    }
    if (
      presentIllnessHistory.ususalRemark &&
      presentIllnessHistory.ususalRemark.trim()
    ) {
      content +=
        serializeUtils.commas(content) + presentIllnessHistory.ususalRemark
    }

    return content
  },
  pastHistory: function (vm) {
    // 婴幼儿期 变应性皮炎（湿疹）史 有 无 ，药物食物过敏史 有 无 ，过敏性鼻炎史：有 无 ，过敏原检测 有 无;
    // 吸入过敏史,牛奶  鸡蛋  鱼虾  尘螨  花粉  其它
    let pastHistory = vm.pastHistory
    if (!pastHistory) return ''

    let subSentences = [
      (data) => {
        let keys = [
          {
            key: 'hasPneumonia',
            render: (value) => {
              return (value ? '有' : '否认') + '重症肺炎'
            },
          },
          {
            key: 'otherDisease',
            render: (value) => {
              return value && value.trim() ? '有' + value : ''
            },
          },
          {
            key: 'allergyHistory',
            render: (value) => {
              return EMR_NAME.had[value + ''] || ''
            },
            suffix: '药物食物过敏史',
            children: {
              isRelated: (value) => {
                return value == '1'
              },
              keys: [{ key: 'allergyHistoryRemark', type: PLACEHOLDER }],
            },
          },
          {
            key: 'hasOthersAllergy',
            render: (value) => {
              return (value ? '有' : '否认') + '吸入过敏原致敏史'
            },
          },
          {
            key: 'dermatitis',
            render: (value) => {
              return EMR_NAME.had[value + ''] + '奶藓(婴儿湿疹)'
            },
          },
          {
            key: 'rash',
            render: (value) => {
              let ret = '经常起荨麻疹(风团)'
              if (value == '0') {
                ret = '不' + ret
              }

              return ret
            },
          },
          {
            key: 'hasNasitisSydrome',
            render: (value) => {
              let ret = ''
              if (pastHistory.hasNasitisSydrome) {
                let nasitisSydromeDetail = ''

                if (pastHistory.nasitisSydromeDetail == 'clearMucus') {
                  nasitisSydromeDetail = '清水涕'
                }

                if (pastHistory.nasitisSydromeDetail == 'yellowMucus') {
                  nasitisSydromeDetail = '黄脓涕'
                }

                ret += `经常流${nasitisSydromeDetail}、连续喷嚏、鼻痒、鼻塞`
              } else {
                ret += '不经常流涕、连续喷嚏、鼻痒、鼻塞'
              }

              return ret
            },
          },
          {
            key: 'nasitis',
            render: (value) => {
              let ret = EMR_NAME.had[value + ''] + '过敏性鼻炎史'
              if (value == '0') return ret

              return ret
            },
          },
          {
            key: 'eyeDiscomfort',
            render: (value) => {
              return EMR_NAME.had[value + ''] + '经常眼痒、揉眼睛、眨眼'
            },
          },
          {
            key: 'nasalCongestion',
            render: (value) => {
              return EMR_NAME.had[value + ''] + '鼻塞、打鼾、张口呼吸'
            },
          },
          // 过敏原检测，移到assExam
          {
            key: 'allergen',
            render: () => {
              let ret = ''
              let hasValid =
                pastHistory.allergen == '1' &&
                ((pastHistory.allergenSources &&
                  pastHistory.allergenSources.length) ||
                  pastHistory.others)
              if (hasValid) {
                ret = '过敏原检测:'
                // 添加后面的文字
                let source = ''
                const mapping = {
                  牛奶: 'milkDiagnosis', // 牛奶的阳性诊断
                  鸡蛋: 'eggDiagnosis', // 蛋的阳性诊断
                  鱼虾: 'seafoodDiagnosis', // 海鲜的阳性诊断
                  // 尘螨: 'dustMitesDiagnosis', // 尘螨的阳性诊断
                  屋尘螨: 'dustMitesDiagnosis1', // 屋尘螨的阳性诊断
                  粉尘螨: 'dustMitesDiagnosis2', // 粉尘螨的阳性诊断
                  花粉: 'pollenDiagnosis', // 花粉的阳性诊断,
                }
                Object.keys(mapping).forEach((key, idx) => {
                  let mappingKeyVal = pastHistory[mapping[key]]
                  if (pastHistory.allergenSources.includes(key)) {
                    source += ',' + key
                    if (mappingKeyVal) {
                      source += mappingKeyVal + 'IU/ml'
                    }
                  }

                  if (idx != pastHistory.allergenSources.length - 1) {
                    source += '、'
                  }
                })

                ret += source

                let others = pastHistory.others
                if (others) {
                  ret += (source ? ',' : '') + others
                }
              }

              return ret
            },
          },
          {
            key: 'supplement',
            render() {
              return pastHistory.supplement || ''
            },
          },
        ]
        return serializeUtils.parse(keys, data, { connector: COMMA_SIGN })
      },
    ]

    return serializeUtils.autoJoin(subSentences, pastHistory)
  },
  personalHistory: function (vm) {
    let personalHistory = vm.personalHistory
    if (!personalHistory) return ''

    let subSentences = [
      (data) => {
        let keys = [
          {
            key: 'fetusOrder',
            render: (value) => {
              return value ? `第${value}胎` : ''
            },
          },
          {
            key: 'childbirthMethod',
            render: (value) => {
              if (value == 'normal') return '顺产'
              if (value == 'early') return '剖宫产'
              return ''
            },
          },
          {
            key: 'childbirthMethodOther',
            render: (value) => {
              if (value == 'monthEnough') return '足月产'
              if (value == 'early') return '早产'
              return ''
            },
          },
          {
            key: 'birthInjury',
            render: (value) => {
              if (value === null) return ''
              return (value ? '有' : '无') + '产伤'
            },
          },
          {
            key: 'asphyxia',
            render: (value) => {
              if (value === null) return ''
              return (value ? '有' : '无') + '窒息'
            },
          },
          {
            key: 'feedingPattern',
            render: (value) => {
              let ret = ''
              if (value === null) return ret
              if (value == 'breastFeeding') {
                ret += '母乳喂养'
                if (personalHistory.breastFeedingMonths) {
                  ret += `至${personalHistory.breastFeedingMonths}月龄`
                }
              } else if (value == 'artificialFeeding') {
                ret += '人工喂养'
                if (personalHistory.artificialFeedingMonths) {
                  ret += `，从${personalHistory.artificialFeedingMonths}月龄开始添加辅食`
                }
              } else if (value == 'mixedFeeding') {
                ret += '混合喂养'
              }
              return ret
            },
          },
          {
            key: 'complementaryFoodOnTime',
            render: (value) => {
              if (value === null) return ''
              return (value ? '' : '没有') + '按时添加辅食'
            },
          },
          {
            key: 'partialEclipse',
            render: (value) => {
              if (value === null) return ''
              return (value ? '有' : '无') + '偏食'
            },
          },
          {
            key: 'specialInGrowth',
            render: (value) => {
              if (value === null) return ''
              let specialInstructions =
                personalHistory.specialInstructions || ''
              specialInstructions =
                value && specialInstructions ? ',' + specialInstructions : ''
              return (
                '生长发育' +
                (value ? '有' : '无') +
                '异常' +
                specialInstructions
              )
            },
          },
          {
            key: 'preventiveInjection',
            render: (value) => {
              if (value === null) return ''
              return (value ? '有' : '没有') + '按时打预防针'
            },
          },
          {
            key: 'hasSideEffects',
            render: (value) => {
              if (value === null) return ''
              let sideEffects = personalHistory.sideEffects || ''
              sideEffects = value && sideEffects ? ',' + sideEffects : ''

              return (value ? '有' : '无') + '不良反应' + `${sideEffects}`
            },
          },
        ]
        return serializeUtils.parse(keys, data, { connector: COMMA_SIGN })
      },
    ]

    return serializeUtils.autoJoin(subSentences, personalHistory)
  },
  familyHistory: function (vm) {
    // 哮喘：父   母   同胞 (   哥哥   姐姐   弟弟   妹妹 )父系和母系家族其它成员  表哥
    // 过敏性鼻炎：父   母   同胞 (   哥哥   姐姐   弟弟   妹妹 )父系和母系家族其它成员  姐弟
    // 食物过敏史：父   母   同胞 (   哥哥   姐姐   弟弟   妹妹 )父系和母系家族其它成员
    // 食物名称：
    // 吸入过敏史：父   母   同胞 (   哥哥   姐姐   弟弟   妹妹 )父系和母系家族其它成员
    // 过敏源：

    let familyHistory = vm.familyHistory
    if (!familyHistory) return ''
    if (familyHistory.hasFamilyHistory === '无') return ''

    let subSentences = [
      (data, prefix, suffix, connector) => {
        let keys = [
          {
            key: 'father',
            render(h) {
              if (!h) return ''
              return '父'
            },
          },
          {
            key: 'mother',
            render(h) {
              if (!h) return ''
              return '母'
            },
          },
          {
            key: 'siblings',
            render(value) {
              let ret = ''
              if (!value) {
                return ret
              }
              ret = '同胞'

              return ret
            },
            connector: '、',
          },
          {
            key: 'siblingsChecks',
            render(value) {
              let ret = ''
              // value 是个数组
              let siblings = value
                .map((item) => {
                  return EMR_NAME[item]
                })
                .join('、')
              if (siblings) ret = `${siblings}`
              return ret
            },
          },
          {
            key: 'other',
            type: PLACEHOLDER,
          },
        ]
        return serializeUtils.parse(keys, data, {
          connector: COMMA_SIGN,
          prefix,
          suffix,
        })
      },
    ]

    // add last food name
    let foodName = familyHistory.foodName
      ? '(' + familyHistory.foodName + ')'
      : ''
    let suckAllergyName = familyHistory.suckAllergyName
      ? '(' + familyHistory.suckAllergyName + ')'
      : ''

    let sentenceSums = [
      {
        data: familyHistory.asthma,
        suffix: '有哮喘史',
      },
      {
        data: familyHistory.rhinallergosis,
        suffix: '有过敏性鼻炎',
      },
      {
        data: familyHistory.allergyHistory,
        suffix: '食物过敏' + foodName,
      },
      {
        data: familyHistory.suckAllergyHistory,
        suffix: '吸入过敏' + suckAllergyName,
      },
      {
        data: familyHistory.others,
        suffix: '其他',
      },
      {
        data: familyHistory.familySmoking,
        suffix: '家族吸烟史',
      },
    ]

    let ret = sentenceSums
      .filter((item) => item.data)
      .map((s) => {
        if (s.suffix === '其他') {
          return s.data ? `其他:${s.data}${FULL_SIGN}` : ''
        } else if (s.suffix === '家族吸烟史') {
          return `家庭成员${s.data ? '有' : '无'}吸烟` + FULL_SIGN
        } else {
          return serializeUtils.autoJoin(
            subSentences,
            s.data,
            { connector: FULL_SIGN },
            { prefix: s.prefix, suffix: s.suffix }
          )
        }
      })
      .join('')

    ret += serializeUtils.autoJoin(subSentences, familyHistory)

    return ret
  },
  // 体格检查
  bodyCheck: function (vm) {
    let diagnosticReport = vm.diagnosticReport
    if (!diagnosticReport) return ''

    let subSentences = [
      (data) => {
        let validPressure = data.bloodPressure.filter((item) => item)
        let hasValid = validPressure.length
        let content = [
          data.tempreture ? `体温${data.tempreture}℃` : '',
          data.pulse ? `脉搏${data.pulse}次／min` : '',
          data.breathing ? `呼吸${data.breathing}次／min` : '',
          data.weight ? `体重${data.weight}kg` : '',
          data.height ? `身高${data.height}cm` : '',
          hasValid ? `血压${data.bloodPressure.join('/')}mmHg` : '',
          data.oxygenSaturation
            ? `经皮测血氧饱和度${data.oxygenSaturation}%`
            : '',
        ]
          .filter((item) => item)
          .join(COMMA_SIGN)

        return content
      },
      (data) => {
        let content = ''

        let contentVals = []
        contentVals.push(
          serializeUtils.isNotNull(data.developmentalStatus)
            ? `发育状况${data.developmentalStatus}`
            : ''
        )
        contentVals.push(
          serializeUtils.isNotNull(data.nutritionalStatus)
            ? `营养状态${data.nutritionalStatus}`
            : ''
        ) //, '中'
        contentVals.push(
          serializeUtils.isNotNull(data.mind) ? `神志${data.mind}` : ''
        ) //, '清晰'

        contentVals.push(
          serializeUtils.isNotNull(data.mentality)
            ? `一般状态${data.mentality}`
            : ''
        )
        contentVals.push(
          data.mentalityChange
            ? `精神意识${data.mentalityChange == '否' ? '没有' : ''}改变${
                (data.mentalityChangeRemark.length &&
                  '(' + data.mentalityChangeRemark.join('、') + ')') ||
                ''
              }`
            : ''
        )

        contentVals.push(
          serializeUtils.isNotNull(data.talk) ? `讲话${data.talk}` : ''
        )

        contentVals.push(
          serializeUtils.isNotNull(data.look)
            ? `${data.look == '黄疸' ? '脸部黄疸' : '脸色' + data.look}`
            : ''
        ) //, '正常'
        contentVals.push(
          serializeUtils.isNotNull(data.cyanosis) ? `${data.cyanosis}发绀` : ''
        ) //, '无'
        contentVals.push(
          serializeUtils.isNotNull(data.triconcaveSign)
            ? `${data.triconcaveSign}三凹征`
            : ''
        )

        contentVals.push(
          `${data.hasEyeDiscomfort || '无'}眼部异常体征${
            data.eyeDiscomfortPart ? ',' + data.eyeDiscomfortPart : ''
          }`
        )

        contentVals.push(
          serializeUtils.isNotNull(data.rash)
            ? `${data.rash}皮疹${data.rashPart ? ',' + data.rashPart : ''}`
            : ''
        ) //, '无'

        contentVals.push(
          serializeUtils.isNotNull(data.superficialLymphNodes)
            ? `${
                data.superficialLymphNodes == '扪及'
                  ? '扪及' + data.superficialLymphNodesPalpation.join('、')
                  : '浅表淋巴结未扪及'
              }`
            : ''
        )
        contentVals.push(
          serializeUtils.isNotNull(data.nasalMucosa)
            ? `鼻粘膜${data.nasalMucosa}`
            : ''
        ) //, '正常'
        contentVals.push(
          serializeUtils.isNotNull(data.nasalSecretions)
            ? `鼻腔分泌物${data.nasalSecretions}`
            : ''
        ) //, '无'

        let left = data.inferiorTurbinateLeft
        left = left ? '左侧' + left : ''
        let right = data.inferiorTurbinateRight
        right = right ? '右侧' + right : ''
        let commas = left || right ? ',' : ''
        let leftAndRigth =
          left || right ? commas + '阻塞鼻腔' + left + right : ''

        contentVals.push(
          serializeUtils.isNotNull(data.inferiorTurbinate)
            ? `下鼻甲${data.inferiorTurbinate + leftAndRigth}`
            : ''
        ) //, '无肿胀'

        contentVals.push(
          serializeUtils.isNotNull(data.pharynx) ? `咽部${data.pharynx}` : ''
        ) //, '无充血'

        let tonsilStatus = serializeUtils.isValid(data.tonsilLeft)
          ? `左侧${data.tonsilLeft}度`
          : ''
        tonsilStatus += serializeUtils.isValid(data.tonsilRight)
          ? `右侧${data.tonsilRight}度`
          : ''
        tonsilStatus = serializeUtils.isValid(tonsilStatus)
          ? ',' + tonsilStatus
          : ''

        contentVals.push(
          serializeUtils.isNotNull(data.tonsil)
            ? `扁桃体${data.tonsil + tonsilStatus}`
            : ''
        ) //, '无肿大'
        contentVals.push(
          serializeUtils.isNotNull(data.surfaceSecretion)
            ? `${data.surfaceSecretion}表面分泌物`
            : ''
        ) //, '无'
        contentVals.push(
          serializeUtils.isNotNull(data.follicularHyperplasia)
            ? `${data.follicularHyperplasia}咽后壁滤泡增生`
            : ''
        ) //, '无'
        contentVals.push(
          serializeUtils.isNotNull(data.posteriorRhinorrhea)
            ? `${data.posteriorRhinorrhea}鼻后孔鼻后滴漏`
            : ''
        ) //, '无'

        content = contentVals.filter((item) => item).join(',')
        return content
      },
      (data) => {
        let content = ''
        let contentVals = []
        contentVals[0] = serializeUtils.isNotNull(data.bilateralRespiratory)
          ? `双侧呼吸运动${data.bilateralRespiratory}`
          : '' //, '对称'
        contentVals[1] = serializeUtils.isNotNull(data.rhythm)
          ? `节律${data.rhythm}`
          : '' //, '整'
        contentVals[2] =
          data.dyspnea == '有'
            ? `${data.dyspneaStatus ? data.dyspneaStatus : '呼吸困难'}`
            : '无呼吸困难' //, '有无呼吸困难'
        contentVals[3] = serializeUtils.isNotNull(data.respiratorySounds)
          ? `听诊呼吸音${data.respiratorySounds}`
          : ''

        contentVals[4] =
          serializeUtils.isNotNull(data.normalThickening) &&
          data.normalThickening != '正常'
            ? `呼吸音${data.normalThickening}`
            : ''
        //'正常'

        // 湿啰音
        let raleAdditional = serializeUtils.isValid(data.raleAdditional)
          ? `(${data.raleAdditional})`
          : ''
        contentVals[5] =
          data.rale === '闻'
            ? `闻${
                Array.isArray(data.raleStatus) ? data.raleStatus.join('、') : ''
              }湿啰音
            ${raleAdditional}`
            : data.rale === '未闻'
            ? '未闻湿啰音'
            : ''

        // 高调干啰音-哮鸣音
        let highPitchedDryAdditional = serializeUtils.isValid(
          data.highPitchedDryAdditional
        )
          ? `(${data.highPitchedDryAdditional})`
          : ''

        let highPitchedDryStatus = data.highPitchedDryStatus || []
        if (
          highPitchedDryStatus.includes('吸气相') &&
          highPitchedDryStatus.includes('呼气相')
        ) {
          highPitchedDryStatus = '双相'
        }
        highPitchedDryStatus = highPitchedDryStatus.toString()

        contentVals[6] =
          (data.highPitchedDry === '闻'
            ? `闻${highPitchedDryStatus}哮鸣音`
            : data.highPitchedDry === '未闻'
            ? '未闻哮鸣音'
            : '') + highPitchedDryAdditional

        // 低调鼾音
        let sonorousRhonchiAdditional = serializeUtils.isValid(
          data.sonorousRhonchiAdditional
        )
          ? `(${data.sonorousRhonchiAdditional})`
          : ''

        if (data.sonorousRhonchi === '闻') {
          let sonorousRhonchiStatus = data.sonorousRhonchiStatus || []
          if (
            sonorousRhonchiStatus.includes('吸气相') &&
            sonorousRhonchiStatus.includes('呼气相')
          ) {
            sonorousRhonchiStatus = '双相'
          }
          highPitchedDryStatus = highPitchedDryStatus.toString()

          contentVals[7] = `${
            data.sonorousRhonchi + sonorousRhonchiStatus
          }鼾音${sonorousRhonchiAdditional}`
        } else if (data.sonorousRhonchi === '未闻') {
          contentVals[7] = '未闻鼾音'
        }

        contentVals[8] = data.otherSignsOfTheLung || ''

        content = contentVals.filter((item) => item).join(',')

        return content ? `\r\n\r\n${content}` : ''
      },
    ]

    return serializeUtils.autoJoin(subSentences, diagnosticReport, {
      connector: FULL_SIGN,
    })
  },
  // 辅助检查
  assExam: function (vm) {
    // let assExam = vm.pastHistory;
    let assExam = vm.assExam
    if (!assExam) return ''

    let subSentences = [
      (data) => {
        let keys = [
          {
            prefix: '用力肺活量(FVC):',
            key: 'vitalCapacity',
            type: PLACEHOLDER,
          },
          {
            prefix: '一秒量(FEV1):',
            key: 'FEV1',
            type: PLACEHOLDER,
          },
          {
            prefix: '一秒率(FEV1/FVC):',
            key: 'oneSecondRate',
            type: PLACEHOLDER,
          },
          {
            prefix: '最大呼气中期流量(MMEF75/25):',
            key: 'maximumRxhalation',
            type: PLACEHOLDER,
          },
          {
            prefix: '一氧化氮(FeNO):',
            key: 'FeNO',
            suffix: 'ppb',
            type: PLACEHOLDER,
          },
          {
            prefix: '一氧化氮(nNO):',
            key: 'NO',
            suffix: 'ppb',
            type: PLACEHOLDER,
          },
          {
            prefix: '血清IgE:',
            key: 'IgE',
            suffix: 'IU/ml',
            type: PLACEHOLDER,
          },
          {
            prefix: '外周血嗜酸性粒细胞比例:',
            key: 'EOSR',
            suffix: '%',
            type: PLACEHOLDER,
          },
          {
            prefix: '',
            key: 'othersTest',
            type: PLACEHOLDER,
          },
          {
            prefix: '支气管激发试验:',
            key: 'bronchialProvocationTest',
            type: VALUE_MAPPING,
          },
          {
            prefix: '支气管舒张试验:',
            key: 'bronchialExtensionTest',
            type: VALUE_MAPPING,
          },
          {
            prefix: '呼气峰流速(PEF)两周波动率:',
            suffix: '%',
            key: 'bronchialProvocationTestNegaVolatility',
            type: PLACEHOLDER,
          },
          {
            prefix: 'ICS和/或白三烯调节剂治疗4-12周FEV1改善率:',
            suffix: '%',
            key: 'maximumRxhalationImprovement',
            type: PLACEHOLDER,
          },
          {
            key: 'allergen',
            render: () => {
              let ret = ''
              let hasValid =
                assExam.allergen + '' === '1' &&
                ((assExam.allergenSources && assExam.allergenSources.length) ||
                  assExam.allergenOthers)
              if (hasValid) {
                ret = '过敏原检测:'
                // 添加后面的文字
                let source = ''
                const mapping = {
                  牛奶: 'milkDiagnosis', // 牛奶的阳性诊断
                  鸡蛋: 'eggDiagnosis', // 蛋的阳性诊断
                  鱼虾: 'seafoodDiagnosis', // 海鲜的阳性诊断
                  尘螨: 'dustMitesDiagnosis', // 尘螨的阳性诊断
                  屋尘螨: 'dustMitesDiagnosis1', // 屋尘螨的阳性诊断
                  粉尘螨: 'dustMitesDiagnosis2', // 粉尘螨的阳性诊断
                  花粉: 'pollenDiagnosis', // 花粉的阳性诊断,
                }
                Object.keys(mapping).forEach((key, idx) => {
                  let mappingKeyVal = assExam[mapping[key]]
                  if (assExam.allergenSources.includes(key)) {
                    source += key
                    if (mappingKeyVal) {
                      source += ':' + mappingKeyVal + '(IU/ml)'
                    }
                    if (idx != assExam.allergenSources.length - 1) {
                      source += ','
                    }
                  }
                })

                if (assExam.allergenOthers) {
                  source += ',其他:' + assExam.allergenOthers
                }
                ret += source
              }

              return ret
            },
          },
          {
            key: 'others',
            type: PLACEHOLDER,
          },
        ]

        return serializeUtils.parse(keys, data, { connector: COMMA_SIGN })
      },
    ]

    return serializeUtils.autoJoin(subSentences, assExam, {
      connector: FULL_SIGN,
    })
  },
  // 诊断
  diagnostic: function (vm, age) {
    let diagnostic = vm.diagnostic
    if (!diagnostic) return ''
    // 获取诊断结果
    function getDiagnocticResult() {
      let val = diagnostic.diagnosticType
      // 控制水平显示
      let controlLevelTestResult = diagnostic.controlLevelTestResult
      let controlLevelTestResultStr =
        (severityLevel[controlLevelTestResult] &&
          severityLevel[controlLevelTestResult].alias) ||
        ''
      // 控制水平
      if (controlLevelTestResultStr) {
        controlLevelTestResultStr = `(控制水平:${controlLevelTestResultStr})`
      }

      // 急性诊断的危重程度
      let asthmaInputStr =
        (diagnostic.asthmaInput &&
          severityLevel[diagnostic.asthmaInput] &&
          severityLevel[diagnostic.asthmaInput].alias) ||
        diagnostic.asthmaInput
      if (asthmaInputStr) {
        asthmaInputStr = `(${asthmaInputStr})`
      }

      // 学龄前儿童症状列表
      let asthmaStatusStr =
        diagnostic.asthmaStatus
          .map((key) => {
            return EMR_NAME[key]
          })
          .join('、') || ''
      if (asthmaStatusStr) {
        asthmaStatusStr = `(五项基本特征：${asthmaStatusStr})`
      }

      let ret = []
      let asthmaMsg = ''
      if (age >= 6) {
        if (val.includes('1')) {
          asthmaMsg = '、哮喘非急性发作期'
          ret.push(`支气管哮喘${controlLevelTestResultStr}`)
        }
        if (val.includes('7')) {
          asthmaMsg = '哮喘非急性发作期'
          ret.push('支气管哮喘?')
        }
        if (val.includes('3')) {
          asthmaMsg = '、哮喘急性发作期'
          ret.push(`支气管急性哮喘${asthmaInputStr}`)
        }
      } else {
        if (val.includes('2')) {
          ret.push(`学龄前反复喘息${controlLevelTestResultStr}`)
        }
        if (val.includes('5')) {
          ret.push(`学龄前反复喘息急性发作${asthmaInputStr}`)
        }
        if (val.includes('6')) {
          ret.push('学龄前反复喘息?')
        }
      }

      if (val.includes('4')) {
        ret.push(`修正诊断:${diagnostic.diagnosticFixContent}`)
      }
      if (val.includes('CVA')) {
        ret.push('咳嗽变异性哮喘(CVA)')
      }
      if (val.includes('SEEMLY_CVA')) {
        ret.push('咳嗽变异性哮喘？')
      }
      // if (controlLevelTestResultStr) {
      //   ret.push(controlLevelTestResultStr);
      // }
      return (ret.length ? ret.join('、') : '') + asthmaMsg + asthmaStatusStr
    }

    let content = getDiagnocticResult()
    content += diagnostic.allergicRhinitis
      ? ((content && COMMA_SIGN) || '') + '过敏性鼻炎'
      : ''

    if (!content) {
      return ''
    }
    content += FULL_SIGN
    if (vm.diagnostic.other)
      content += '（其他备注：' + vm.diagnostic.other + '）。'
    return content
  },
  // 以前的治疗方案
  diagnosticRequestCompatible(vm) {
    let diagnosticRequest = vm.diagnosticRequest
    let content = ''
    if (!diagnosticRequest) return content

    let longTermText = diagnosticRequest.longtermTreatmentTpl
    let emergencyText = diagnosticRequest.emergencyTreatmentTpl
    let otherTreatmentTpl = diagnosticRequest.otherTreatmentTpl
    if (longTermText) {
      content += '长期治疗方案:\r\n' + longTermText + '\r\n'
    }
    if (emergencyText) {
      content += `急性发作缓解治疗方案:\r\n ${emergencyText}\r\n`
    }
    if (otherTreatmentTpl) {
      content += `附加治疗方案:\r\n ${otherTreatmentTpl} \r\n`
    }

    if (diagnosticRequest.isDesensitizationTherapy) {
      content += '进行过脱敏治疗\r\n'
    }

    if (diagnosticRequest.desensitizationTherapyRemark) {
      content += `${diagnosticRequest.desensitizationTherapyRemark}\r\n`
    }

    return content
  },
  // 结构后的治疗方法
  diagnosticRequest(vm) {
    // if (!vm.diagnosticRequest) {
    //   return ''
    // }
    let diagnosticRequest = vm.diagnosticRequest
    // 旧版
    if (diagnosticRequest.version != '2020-12-02') {
      return this.diagnosticRequestCompatible(vm)
    }

    let content = ''
    let longtermRegular = diagnosticRequest.longtermRegular
    let longtermWorsen = diagnosticRequest.longtermWorsen
    let emergency = diagnosticRequest.emergency
    let others = diagnosticRequest.others
    let remark = diagnosticRequest.remark
    let toString = (data, isEmergency = false) => {
      let content = ''
      data.responses.forEach((drug) => {
        // 綠區
        let lowQuantityText = drug.quantityPerDosageLow
          ? drug.quantityPerDosageLow + drug.drugUnit
          : ''
        let low = drug.frequencyLatinLow
          ? ` 绿区：${lowQuantityText} 
          ${drug.frequencyLatinLow} ${drug.remarkLow};`
          : ''

        // 紅區
        let highQuantityText = drug.quantityPerDosageHigh
          ? drug.quantityPerDosageHigh + drug.drugUnit
          : ''
        let high = drug.frequencyLatinHigh
          ? ` 红区：${highQuantityText} 
          ${drug.frequencyLatinHigh} ${drug.remarkHigh};`
          : ''

        // 黃區
        let mediumQuantityText = drug.quantityPerDosageMedium
          ? drug.quantityPerDosageMedium + drug.drugUnit
          : ''
        let meidum = drug.frequencyLatinMedium
          ? ` 黄区：${mediumQuantityText} 
          ${drug.frequencyLatinMedium} ${drug.remarkMedium};`
          : ''

        let emergencyHigh =
          drug.frequencyLatinHigh && isEmergency
            ? `${drug.quantityPerDosageHigh}${drug.drugUnit} 
            ${drug.frequencyLatinHigh} ${drug.remarkHigh};`
            : ''
        if (isEmergency) {
          content += `${drug.commonName} 
          (${drug.drugSpec}) ${emergencyHigh}\r\n`
        } else {
          content += `${drug.commonName} 
          (${drug.drugSpec}) ${low}${meidum}${high}\r\n`
        }
      })
      return content
    }

    if (longtermRegular.responses.length) {
      content +=
        '长期治疗方案规律用药:\r\n' + toString(longtermRegular) + '\r\n'
    }
    if (longtermWorsen.responses.length) {
      content +=
        '长期治疗方案恶化应急用药:\r\n' + toString(longtermWorsen, 1) + '\r\n'
    }
    if (emergency.responses.length) {
      content += '急性发作缓解治疗方案:\r\n' + toString(emergency, 1) + '\r\n'
    }
    if (others.content) {
      content += '附加治疗方案（生物制剂）:\r\n' + others.content + '\r\n'
    }
    if (remark.content) {
      content += '其他:\r\n' + remark.content + '\r\n'
    }
    if (diagnosticRequest.isDesensitizationTherapy) {
      content += '进行过脱敏治疗\r\n'
    }

    if (diagnosticRequest.desensitizationTherapyRemark) {
      content += `${diagnosticRequest.desensitizationTherapyRemark}\r\n`
    }

    return content
  },
  // 复诊的
  reviewChiefComplaint(vm) {
    let reviewChiefComplaint = vm.reviewChiefComplaint
    if (!reviewChiefComplaint) return ''

    // main 控制整句是否有效
    if (
      serializeUtils.isPass(
        !reviewChiefComplaint.cough &&
          !reviewChiefComplaint.wheezing &&
          !reviewChiefComplaint.remark
      )
    )
      return ''

    let isNotValid = serializeUtils.isPass(
      !reviewChiefComplaint.cough && !reviewChiefComplaint.wheezing
    )

    // sub sentences
    let subSentences = [
      function (data) {
        let prefix = '上次就诊至今',
          content = ''

        if (data.cough == '有' && data.wheezing == '有') {
          content += prefix + '咳嗽' + '伴喘息'
        } else if (data.cough == '有') {
          content += prefix + '咳嗽,无喘息'
        } else if (data.wheezing == '有') {
          content += prefix + '无咳嗽,有喘息'
        } else {
          content += prefix + '无咳嗽,无喘息'
        }

        return isNotValid ? '' : content
      },
      function (data) {
        let prefix = '于'
        let keys = [
          { key: 'weeks', alias: 'week', type: PLACEHOLDER_MAPPING },
          { key: 'days', alias: 'day', type: PLACEHOLDER_MAPPING },
        ]

        // keys 随意组合
        let content = serializeUtils.randomCombination(data, keys)

        return isNotValid ? '' : content ? prefix + content + '前出现' : ''
      },
      function (data) {
        let prefix = '长期控制治疗药物'
        let content = ''
        if (data.longTermAdjustment) {
          content += prefix + data.longTermAdjustment + '调整'
        }
        return isNotValid ? '' : content
      },
      function (data) {
        return data.remark
      },
    ]

    let ret = serializeUtils.autoJoin(subSentences, reviewChiefComplaint)

    return ret
  },
  /**
   * 检查结果
   */
  checkResult(vm) {
    return (vm.checkResult && vm.checkResult.result) || ''
  },
}

// 急性哮喘的严重级别
const severityLevel = {
  low: {
    value: 'low',
    alias: '轻度',
  },
  medium: {
    value: 'medium',
    alias: '中度',
  },
  high: {
    value: 'high',
    alias: '重度',
  },
  danger: {
    value: 'danger',
    alias: '危重度',
  },
  without_control: {
    value: 'without_control',
    alias: '未得到控制',
  },
  partial_control: {
    value: 'partial_control',
    alias: '部分控制',
  },
  well_control: {
    value: 'well_control',
    alias: '控制良好',
  },
  under_control: {
    value: 'under_control',
    alias: '完全控制',
  },
}
